import {
  reqCart,
  reqUpdateCart,
  reqUpdateAll,
  reqAddOrUpdateCount,
  reqDeleteGoods
} from '../../api/index'
Page({

  data: {
    //存储购物车数据
    goodArr: [],
    total: 0,
    totalCount: 0,
    selected: false
  },

  onShow(options) {
    //获取购物车数据
    this.getCartList();
  },
  async getCartList() {
    let result = await reqCart();
    if (result.code == 200) {
      this.setData({
        goodArr: result.data
      });
      //计算总价
      this.computedTotal();
      //计算个数
      this.computedCount();
      //计算全选
      this.AllChecked();
    }
  },

  //计算总价
  computedTotal() {
    let total = this.data.goodArr.reduce((prev, next) => {
      if (next.isChecked == 1) {
        prev += next.price * next.count;
      }
      return prev;
    }, 0);
    this.setData({
      total
    })
  },
  //计算一共多少件商品
  computedCount() {
    let total = this.data.goodArr.reduce((prev, next) => {
      if (next.isChecked == 1) {
        prev += next.count;
      }
      return prev;
    }, 0);
    this.setData({
      totalCount: total
    })
  },
  //计算全选
  AllChecked() {
    let selected = this.data.goodArr.every(item => item.isChecked == 1);
    this.setData({
      selected
    })
  },
  //更新状态
  async changeHandler(e) {
    let goodsId = e.currentTarget.dataset.goodsid;
    let isChecked = e.detail ? 1 : 0;
    try {
      await reqUpdateCart({
        goodsId,
        isChecked
      });
      this.getCartList();
    } catch (error) {

    }
  },

  //全选按钮回调
  async updateAll(e) {
    let isChecked = e.detail ? 1 : 0;
    try {
      await reqUpdateAll(isChecked);
      this.getCartList();
    } catch (error) {

    }
  },
  //更新数量
  async updateCount(e) {
    let newCount = e.detail;
    let oldCount = e.currentTarget.dataset.count;
    let count = newCount - oldCount;
    let goodsId = e.currentTarget.dataset.goodsid;
    try {
      await reqAddOrUpdateCount({
        count,
        goodsId
      });
      this.getCartList();
    } catch (error) {

    }
  },
  //删除商品
  removehandler(e) {
    let goodsId = e.currentTarget.dataset.id;
    wx.showModal({
      cancelColor: 'cancelColor',
      title: '删除商品',
      success: async() => {
        try {
          await reqDeleteGoods(goodsId)
          this.getCartList();
        } catch (error) {

        }
      }
    })
  },
  //计算
  goOrder(){
    wx.navigateTo({
      url: '/pages/order-detail/index',
    })
  }

})